from fastapi import APIRouter, Depends, Form, Request, HTTPException,Cookie
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from models import Area
from database import get_db
from typing import Optional
from fastapi.responses import RedirectResponse
from datetime import datetime
from utils import validate_session

router = APIRouter()
templates = Jinja2Templates(directory="templates")

# 区域管理首页
@router.get("/areas")
async def list_areas(
    request: Request,
    SessionId: Optional[str] = Cookie(None),
    UserName: Optional[str] = Cookie(None),
    search: Optional[str] = None,
    page: int = 1,
    page_size: int = 10,
    db: Session = Depends(get_db)
):
    if not SessionId or not UserName or not validate_session(SessionId, UserName):
        return RedirectResponse(url="/")

    query = db.query(Area).filter(Area.DeadTime == None)
    
    if search:
        query = query.filter(Area.AreaName.ilike(f"%{search}%"))
    
    total_items = query.count()
    total_pages = (total_items + page_size - 1) // page_size
    
    areas = query.order_by(Area.AreaId)\
                .offset((page - 1) * page_size)\
                .limit(page_size)\
                .all()
    
    return templates.TemplateResponse("areas.html", {
        "request": request,
        "areas": areas,
        "search": search,
        "current_page": page,
        "total_pages": total_pages,
        "page_size": page_size
    })

# 添加区域
@router.post("/areas")
async def add_area(
    request: Request,
    AreaName: str = Form(...),  # 使用 Form 而不是查询参数
    Latitude: Optional[float] = Form(None),
    Longitude: Optional[float] = Form(None),
    db: Session = Depends(get_db)
):
    try:
        # 检查区域名称是否已存在
        existing_area = db.query(Area).filter(Area.AreaName == AreaName, Area.DeadTime == None).first()
        if existing_area:
            raise HTTPException(status_code=400, detail="区域名称已存在")
        
        new_area = Area(
            AreaName=AreaName,
            Latitude=Latitude,
            Longitude=Longitude
        )
        
        db.add(new_area)
        db.commit()
        
        return RedirectResponse(url="/areas?success=区域添加成功", status_code=303)
    except Exception as e:
        db.rollback()
        return RedirectResponse(url=f"/areas?error={str(e)}", status_code=303)
    
# 更新区域
@router.post("/areas/{area_id}")
async def update_area(
    request: Request,
    area_id: int,
    AreaName: str = Form(...),
    Latitude: Optional[float] = Form(None),
    Longitude: Optional[float] = Form(None),
    db: Session = Depends(get_db)
):
    try:
        area = db.query(Area).filter(Area.AreaId == area_id, Area.DeadTime == None).first()
        if not area:
            raise HTTPException(status_code=404, detail="区域不存在")
        
        # 检查区域名称是否与其他区域冲突
        existing_area = db.query(Area)\
                         .filter(Area.AreaId != area_id, 
                                 Area.AreaName == AreaName,
                                 Area.DeadTime == None)\
                         .first()
        if existing_area:
            raise HTTPException(status_code=400, detail="区域名称已存在")
        
        area.AreaName = AreaName
        area.Latitude = Latitude
        area.Longitude = Longitude
        area.UpdateTime = datetime.now()
        
        db.commit()
        
        return RedirectResponse(url="/areas?success=区域更新成功", status_code=303)
    except Exception as e:
        db.rollback()
        return RedirectResponse(url=f"/areas?error={str(e)}", status_code=303)

# 删除区域
@router.post("/areas/{area_id}/delete")
async def delete_area(
    request: Request,
    area_id: int,
    db: Session = Depends(get_db)
):
    try:
        area = db.query(Area).filter(Area.AreaId == area_id, Area.DeadTime == None).first()
        if not area:
            raise HTTPException(status_code=404, detail="区域不存在")
        
        # 软删除
        area.DeadTime = datetime.now()
        db.commit()
        
        return RedirectResponse(url="/areas?success=区域删除成功", status_code=303)
    except Exception as e:
        db.rollback()
        return RedirectResponse(url=f"/areas?error={str(e)}", status_code=303)